/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.mobiubiq.directory.client.frame;

import org.kalmeo.kuix.core.Kuix;
import org.kalmeo.kuix.core.KuixConstants;
import org.kalmeo.kuix.widget.Screen;
import org.kalmeo.util.frame.Frame;
import org.kalmeo.util.frame.FrameHandler;
import org.mobiubiq.directory.client.KuixClient;

/**
 *
 * @author Marnix Renne
 */
public abstract class AbstractBaseFrame implements Frame {
    protected Screen screen;
    
    public AbstractBaseFrame() {
        super();
    }
    
    public void onAdded() {
        showScreen();
    }

    public final void onRemoved() {
        cleanUp();
    }

    public boolean onMessage(Object identifier, Object[] arguments) {
        boolean result = true;
        if ("exit".equals((String) identifier)) {
            // get the midlet instance to invoke the Destroy() method
            KuixClient.getDefault().destroyImpl();
            //if the event has been processed, we return 'false' to avoid event forwarding to other frames
            result = false;
        }
        if ("about".equals(identifier)) {
            // display a popup message
            Kuix.alert(Kuix.getMessage("CREDITS"), KuixConstants.ALERT_OK);
            result = false;
        }
        if ("exitConfirm".equals(identifier)) {
            // display a popup message
            Kuix.alert(Kuix.getMessage("EXIT_CONFIRM"), KuixConstants.ALERT_YES | KuixConstants.ALERT_NO, null, "exit", null, null);
            result = false;
        }
        if("back".equals(identifier)) {
            //Kuix.getFrameHandler().removeFrame(this);
            //AbstractBaseFrame topframe = (AbstractBaseFrame) Kuix.getFrameHandler().getTopFrame();
            //topframe.showScreen();
            remove();
            result = false;
        }
        return result;
    }

    public final void showScreen() {
        if (screen == null) {
            screen = loadScreen();
        }
        screen.setCurrent();
    }
    
    public final void remove() {
        FrameHandler handler = Kuix.getFrameHandler();
        handler.removeFrame(this);
        AbstractBaseFrame frame = (AbstractBaseFrame) handler.getTopFrame();
        if(frame != null) {
            frame.showScreen();
        }
    }
    
    protected abstract Screen loadScreen();
    
    protected void cleanUp() {
        screen.cleanUpChildren();
        screen.cleanUp();
        screen = null;
    }
}
